package org.example.liuy.controller;

import com.sun.net.httpserver.HttpExchange;
import lombok.extern.slf4j.Slf4j;
import org.example.liuy.annotation.GetMapping;
import org.example.liuy.annotation.RestController;
import org.example.liuy.service.session.IntelligentSessionService;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * 会话控制器
 */
@Slf4j
@RestController
public class SessionController extends BaseController{

    public SessionController(IntelligentSessionService sessionManager) {
        super(sessionManager);
    }

    /**
     * 处理会话创建请求
     * @param exchange HTTP交换对象
     * @throws IOException IO异常
     */
    @GetMapping("/{customerId}/session")
    public void handleSessionRequest(HttpExchange exchange) throws IOException {
        try {
            Integer customerId = extractCustomerId(exchange);
            if (customerId == null) {
                sendResponse(exchange, 400, "Invalid customer ID");
                return;
            }

            CompletableFuture<String> sessionFuture = sessionManager.createSession(customerId);
            String sessionKey = sessionFuture.get();

            sendResponse(exchange, 200, sessionKey);
        } catch (Exception e) {
            log.error("Session creation failed", e);
            sendResponse(exchange, 500, "Internal Server Error");
        }
    }

    /**
     * 从请求路径中提取客户ID
     */
    private Integer extractCustomerId(HttpExchange exchange) {
        String[] pathParts = exchange.getRequestURI().getPath().split("/");
        if (pathParts.length < 3) {
            return null;
        }

        try {
            return Integer.valueOf(pathParts[pathParts.length - 2]);
        } catch (NumberFormatException e) {
            return null;
        }
    }


}